package xyz.xwls.bootadmin.sys.controller;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import xyz.xwls.bootadmin.common.CommonResult;
import xyz.xwls.bootadmin.component.BaseController;
import xyz.xwls.bootadmin.sys.domain.User;
import xyz.xwls.bootadmin.sys.service.UserService;
import xyz.xwls.bootadmin.sys.vo.PageResult;
import xyz.xwls.bootadmin.sys.vo.UserVo;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.Date;

/**
 * @author WZW
 * @date 2020/4/13
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Data
    static class UserParam{
        @Min(1)
        private Integer page;
        @Max(100)
        private Integer limit;
        private String username;
        private String mobile;
        private String email;
        private Integer status = 2;
    }

    @GetMapping("/list")
    public CommonResult<?> list(@Valid UserParam userParam, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getErrors(bindingResult);
        }
        log.debug("userParam : {}", userParam);
        if (userParam.page == null){
            userParam.page = 1;
        }
        if (userParam.limit == null){
            userParam.limit = 10;
        }
        User user = new User();
        user.setUsername(userParam.getUsername());
        user.setMobile(userParam.getMobile());
        user.setEmail(userParam.getEmail());
        Integer status = userParam.getStatus();
        user.setStatus(status);
        PageResult<UserVo> pageResult = userService.list(userParam.page, userParam.limit, user);
        return CommonResult.success(pageResult);
    }

    @PostMapping
    public CommonResult<?> save(@RequestBody @Valid User user, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getErrors(bindingResult);
        }
        user.setStatus(1);
        user.setCreateTime(new Date());
        userService.save(user);
        return CommonResult.success();
//        return CommonResult.success(UserServiceImpl.convert(user));
    }

    @PutMapping
    public CommonResult<?> update(@RequestBody @Valid User user, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getErrors(bindingResult);
        }
        userService.update(user);
        return CommonResult.success();
    }



}
